package com.chuangyang.fixboxmaster.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxlib.widgets.ImageButton;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.B2BOrderDetail;
import com.chuangyang.fixboxmaster.bean.DateTimeEvent;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.B2BMapViewActivity;
import com.chuangyang.fixboxmaster.ui.B2BPartListDetailActivity;
import com.chuangyang.fixboxmaster.ui.GetPartActivity;
import com.chuangyang.fixboxmaster.ui.ModuleActivity;
import com.chuangyang.fixboxmaster.ui.ReceiveCodeActivity;
import com.chuangyang.fixboxmaster.ui.widgets.timepick.SelectTimeDateView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by vanshu on 15/4/10 14:03.
 */
public class B2BOrderDetailFragment extends BaseFragment implements View.OnClickListener, SelectTimeDateView.TimePickerClick {
    private View mContentView;
    private LinearLayout mOrderStatusLayout;
    private TextView mOrderStatus;
    private TextView mOrderId;
    private TextView mOrderType;
    private TextView mOrderPriceNum;
    private TextView mOrderDes;
    private TextView mOrderUserName;
    private TextView mOrderAppointTime;
    private TextView mOrderAddress;
    private ImageButton mDialPhone;
    private String orderId;
    private String phoneNumber;
    private Button mBtnBottom;
    private String currentOrderStatus;
    private static final int ACTIVITY_INTENT_GET_CODE = 10;
    private B2BOrderDetail orderDetail;
    private LinearLayout mRepairSuccLin;
    private TextView mPriceView;
    private TextView mOrderBrand;
    private TextView mOrderModel;
    private TextView mOrderServiceType;
    private TextView mOrderIntegral;
    private ScrollView mScrollView;
    private LinearLayout mSelectAppointTime;
    private SelectTimeDateView mTimePicker;// 时间控件
    private DateTimeEvent mTimeEvent;// 获取预约时间, 是否预约
    private TextView mPartStatus;
    private ImageButton mBtnChangePart;
    private LinearLayout mPartStatusLayout;
    private String mDate;
    private TextView mKehuMeomo;
    private LinearLayout mBottomLayout;
    private Button mBtnAddPart;
    private Button mBtnFinishOrder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_b2b_order_detail, container, false);
        orderId = getArguments().getString(ModuleActivity.ORDER_ID);
        mOrderStatusLayout = (LinearLayout) mContentView.findViewById(R.id.order_status_layout);
        mOrderStatus = (TextView) mContentView.findViewById(R.id.order_status);
        mOrderId = (TextView) mContentView.findViewById(R.id.order_id);
        mOrderType = (TextView) mContentView.findViewById(R.id.order_repair_type);
        mOrderPriceNum = (TextView) mContentView.findViewById(R.id.order_repair_num);
        mOrderDes = (TextView) mContentView.findViewById(R.id.order_des);
        mOrderUserName = (TextView) mContentView.findViewById(R.id.order_user_name);
        mDialPhone = (ImageButton) mContentView.findViewById(R.id.btn_dial);
        mDialPhone.setOnClickListener(this);
        mOrderAppointTime = (TextView) mContentView.findViewById(R.id.order_appoint_time);
        mOrderAddress = (TextView) mContentView.findViewById(R.id.order_user_address);
        mBtnBottom = (Button) mContentView.findViewById(R.id.btn_bottom);
        mBtnBottom.setOnClickListener(this);
        mRepairSuccLin = (LinearLayout) mContentView.findViewById(R.id.repair_succ_lin);
        mRepairSuccLin.setOnClickListener(this);
        mPriceView = (TextView) mContentView.findViewById(R.id.order_repair_price);
        mOrderBrand = (TextView) mContentView.findViewById(R.id.order_brand);
        mOrderModel = (TextView) mContentView.findViewById(R.id.order_model);
        mOrderServiceType = (TextView) mContentView.findViewById(R.id.order_service_type);
        mOrderIntegral = (TextView) mContentView.findViewById(R.id.order_integral);
        mKehuMeomo = (TextView) mContentView.findViewById(R.id.kehu_des);
        mScrollView = (ScrollView) mContentView.findViewById(R.id.b2b_detail_scroll_view);
        mSelectAppointTime = (LinearLayout) mContentView.findViewById(R.id.select_time_dialog);
        mSelectAppointTime.setOnClickListener(this);
        LinearLayout mOrderAddressLayout = (LinearLayout) mContentView.findViewById(R.id.ll_order_user_address);
        mOrderAddressLayout.setOnClickListener(this);
        mPartStatus = (TextView) mContentView.findViewById(R.id.part_status);
        mBtnChangePart = (ImageButton) mContentView.findViewById(R.id.btn_change_part);
        mBtnChangePart.setOnClickListener(this);
        mPartStatusLayout = (LinearLayout) mContentView.findViewById(R.id.part_status_layout);
        mBottomLayout = (LinearLayout) mContentView.findViewById(R.id.ll_bottom);
        mBtnAddPart = (Button) mContentView.findViewById(R.id.btn_add_part);
        mBtnFinishOrder = (Button) mContentView.findViewById(R.id.btn_complete_order);
        mBtnAddPart.setOnClickListener(this);
        mBtnFinishOrder.setOnClickListener(this);
        setHasOptionsMenu(true);
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        mTimeEvent = new DateTimeEvent(df.format(new Date()), 0);
        mTimePicker = new SelectTimeDateView(getActivity(), mTimeEvent.getDateAndTime());
        mDate = mTimePicker.getFirstDate();
    }

    private void loadData() {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        addRequest(new GsonRequest<>(FixBoxApi.B2B_ORDER_DETAIL, param, B2BOrderDetail.class, responseListener));
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private Response.Listener<B2BOrderDetail> responseListener = new Response.Listener<B2BOrderDetail>() {
        @Override
        public void onResponse(B2BOrderDetail response) {
            if (getActivity() != null && isAdded()) {
                orderDetail = response;

                mOrderId.setText("" + response.result.ORDER_NO);
                mOrderType.setText(response.result.PRODUCT_NAME);
                mOrderPriceNum.setText("￥" + response.result.SERVICE_PRICE + " × " + response.result.PRODUCT_NUMS);
                mOrderDes.setText(response.result.SERVICE_MEMO);
                mOrderUserName.setText(response.result.LINK_MAN);
                mOrderAddress.setText(response.result.LINK_ADDRESS);
                phoneNumber = response.result.LINK_PHONE1;
                mOrderAppointTime.setText(response.result.PLAN_TIME);
                if (response.result.PLAN_TIME == null) {
                    mSelectAppointTime.setVisibility(View.GONE);
                }
                currentOrderStatus = response.result.ORDER_STATUS;
                mPriceView.setText(response.result.totalPrice + "元");
                mOrderBrand.setText(response.result.PRODUCT_BRAND + response.result.PRODUCT_NAME);
                mOrderModel.setText(response.result.PRODUCT_MODEL);
                mOrderServiceType.setText(response.result.SERVICE_NAME);
                mOrderIntegral.setText(String.valueOf(response.result.INTEGRALS));
                mPartStatus.setText("配件状态    " + response.result.PARTS_STATUS);
                mKehuMeomo.setText(response.result.ORDER_MEMO);
                if (response.result.transactionId == 1) {
                    mBtnAddPart.setVisibility(View.VISIBLE);                }
                showResult();
                getCurrentState();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dial:
                StringUtils.dialPhone(getActivity(), phoneNumber);
                break;

            case R.id.btn_bottom:
                if (currentOrderStatus.equals("已发布")) {
                    takeOrder();
                }
                break;
            case R.id.ll_order_user_address:
                Intent intentMap = new Intent();
                intentMap.putExtra("latitude",orderDetail.result.latitude);
                intentMap.putExtra("longitude", orderDetail.result.longitude);
                intentMap.setClass(getActivity(), B2BMapViewActivity.class);
                startActivity(intentMap);
                break;

            case R.id.select_time_dialog:
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
                mTimeEvent = new DateTimeEvent(df.format(new Date()), 0);
                mTimePicker = new SelectTimeDateView(getActivity(), mTimeEvent.getDateAndTime());
                mTimePicker.showAtLocation(mContentView.findViewById(R.id.root), Gravity.BOTTOM, 0, 0);
                mTimePicker.setmOKBtnClickListener(B2BOrderDetailFragment.this);
                break;
            case R.id.repair_succ_lin:
                Intent intent = new Intent();
                intent.putExtra("id", orderId);
                intent.setClass(getActivity(), B2BPartListDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_change_part:
                intent = new Intent();
                intent.putExtra("order", orderDetail.result);
                intent.putExtra("isRechoose", "1");
                intent.setClass(getActivity(), GetPartActivity.class);
                startActivity(intent);
                break;

            case R.id.btn_add_part:
                Intent intent2 = new Intent();
                intent2.putExtra("order", orderDetail.result);
                intent2.setClass(getActivity(), GetPartActivity.class);
                startActivity(intent2);
                break;

            case R.id.btn_complete_order:
                Intent intent3 = new Intent(getActivity(), ReceiveCodeActivity.class);
                intent3.putExtra("orderId", String.valueOf(orderDetail.result.Id));
                intent3.putExtra("number",orderDetail.result.phoneNumber);
                startActivityForResult(intent3, ACTIVITY_INTENT_GET_CODE);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_INTENT_GET_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String price = data.getStringExtra("price");
                confirmOrderPrice(price);
            }
        }
    }

    private void confirmOrderPrice(String price) {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        param.put("totalPrice", price);
//       addRequest(new GsonRequest<>(FixBoxApi.ORDER_CONFIRM_ORDER, param, OrderDetail.class, responseListener));
    }

    private void takeOrder() {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        addRequest(new GsonRequest<>(FixBoxApi.B2B_TAKE_ORDER, param, B2BOrderDetail.class, responseListener));
    }

    private void getCurrentState() {
        if (currentOrderStatus.equals("已发布")) {
            moveToState0();
        } else if (currentOrderStatus.equals("处理中")) {
            moveToState1();
        } else if (currentOrderStatus.equals("已完成")) {
            moveToState3();
        } else if (currentOrderStatus.equals("取消未审核") || currentOrderStatus.equals("取消已审核")) {
            moveToStateCancel();
        } else if (currentOrderStatus.equals("停滞中")) {
            moveToState4();
        }
    }

    private void moveToState0() {  //等待接单
        mOrderStatusLayout.setVisibility(View.GONE);
        mDialPhone.setVisibility(View.GONE);
        mBtnBottom.setVisibility(View.VISIBLE);
        mBtnBottom.setText("接单");
        mRepairSuccLin.setVisibility(View.VISIBLE);
        mPartStatusLayout.setVisibility(View.GONE);
        mBottomLayout.setVisibility(View.GONE);
    }

    private void moveToState1() { //已接单，未维修完成
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("订单正在处理中");
        mOrderStatus.setTextColor(getResources().getColor(R.color.blue_background));
        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);
        mBtnBottom.setVisibility(View.VISIBLE);
        if (orderDetail.result.PARTS_STATUS == null) {
            mPartStatusLayout.setVisibility(View.GONE);
        } else {
            mPartStatusLayout.setVisibility(View.VISIBLE);
            mBtnChangePart.setVisibility(View.INVISIBLE);
        }
        mRepairSuccLin.setVisibility(View.VISIBLE);
        mBtnBottom.setVisibility(View.GONE);
        mBottomLayout.setVisibility(View.VISIBLE);
    }

    private void moveToState2() { //等待用户付款
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("等待用户付款");
        mOrderStatus.setTextColor(getResources().getColor(R.color.blue_background));

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mRepairSuccLin.setVisibility(View.VISIBLE);
    }

    private void moveToState3() { //已完成订单
        mOrderStatus.setText("订单已完成，收到用户" + orderDetail.result.totalPrice + "元");
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setTextColor(getResources().getColor(R.color.blue_background));

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mBtnChangePart.setVisibility(View.GONE);
        mPartStatusLayout.setVisibility(View.VISIBLE);
        mBottomLayout.setVisibility(View.GONE);
    }

    private void moveToStateCancel() { //已取消订单
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("订单已取消");

        mDialPhone.setClickable(false);
        mDialPhone.setFocusable(false);
        mDialPhone.setBackgroundResource(R.drawable.grey_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mRepairSuccLin.setVisibility(View.GONE);
        mBottomLayout.setVisibility(View.GONE);
    }


    private void moveToState4() {
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("订单正在停滞中");
        mOrderStatus.setTextColor(getResources().getColor(R.color.red_background));
        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mRepairSuccLin.setVisibility(View.VISIBLE);
        mPartStatusLayout.setVisibility(View.VISIBLE);
        mBottomLayout.setVisibility(View.GONE);
    }

    public void updateView() {
        loadData();
    }

    public ScrollView getScrollView() {
        return mScrollView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.b2b_order_detail_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_online_service:
                StringUtils.dialPhone(getActivity(), orderDetail.result.phoneNumber);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onOKClickCallBack(String date) {
        setDate(mOrderUserName.getText().toString(), date);  // TODO  null point
    }


    private void setDate(String name, String date) {
        if (date != null && !date.equals("")) {
            showDialog(name, date);
        }
    }

    private Response.Listener<B2BOrderDetail> changeAppointTimeResponseListener = new Response.Listener<B2BOrderDetail>() {
        @Override
        public void onResponse(B2BOrderDetail response) {
            if (getActivity() != null && isAdded()) {
                if (response.success == 1) {
                    loadData();
                }
            }
        }
    };


    private void showDialog(String name, String date) {
        final String currentDate = date;
        AlertDialog.Builder cancelOrderDlg = new AlertDialog.Builder(getActivity());
        cancelOrderDlg.setTitle("确认信息");
        cancelOrderDlg.setMessage("您要把" + name + "先生的预约时间改为" + date);
        cancelOrderDlg.setCancelable(true);
        View dialogView = getActivity().getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
        final EditText mContent = (EditText) dialogView.findViewById(R.id.et_content);
        cancelOrderDlg.setView(dialogView);
        cancelOrderDlg.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        cancelOrderDlg.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String reason = mContent.getText().toString();
                if (reason == null || reason.equals("")) {
                    Toast.makeText(getActivity(), "请输入修改理由", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, String> param = new HashMap<>();
                param.put("id", orderId);
                param.put("startTime", currentDate);
                param.put("moddifyReason", reason);
                addRequest(new GsonRequest<>(FixBoxApi.GET_CHANGE_APPOINT_TIME, param, B2BOrderDetail.class, changeAppointTimeResponseListener));
            }
        });
        cancelOrderDlg.show();

    }

}